import { Vue, Component, Watch } from 'vue-property-decorator';
import '@/styles/animation.less';
import style from '@/styles/views/home.module.less';
import { Route } from 'vue-router';
import { Dialog, Tabbar, TabbarItem } from 'vant';
import { ITabBarType } from '@/interfaces/store.interface';
import { ISimpleDevice } from '@/interfaces/device.interface';
import { IResponse } from '@/interfaces/common.interface';
import { IUser } from '@/interfaces/auth.interface';
import Utils from '@/common/Utils';

Vue.use(Dialog);

interface HistoryPath {
  index: number;
  fullPath?: string;
}

@Component({
  components: {
    'van-tabbar-item': TabbarItem,
    'van-tabbar': Tabbar
  },
  sockets: {
    error(msg) {
      this.$message.error(msg);
    },
    success(msg) {
      this.$message.success(msg);
    },
    devices(data: ISimpleDevice[]) {
      this.$store.commit('update', { devices: data });
      this.$forceUpdate();
    },
    rooms(data) {
      this.$store.commit('update', { rooms: data });
      this.$forceUpdate();
    },
    managers(data: IUser[]) {
      this.$store.commit('update', { managers: data });
      this.$forceUpdate();
    }
  }
})
export default class Home extends Vue {
  private transitionName = 'slide-left';
  private historyRouter: Array<HistoryPath> = [];
  private active: ITabBarType = 'room-list';
  private showAuthorization = false;
  private loading = false;

  private get accountInfo(): IUser {
    return this.$store.state.accountInfo;
  }

  @Watch('active', { immediate: true })
  watchActive(v: ITabBarType) {
    this.$store.commit('update', { activeBar: v });
    this.$router.push({ name: v });
  }

  @Watch('accountInfo', { immediate: true })
  watchAccountInfo(v: IUser) {
    if (!Utils.isObject(v) || !v.acoid) {
      this.$router.push({name: 'room-list' })
      this.showAuthorization = true;
    } else {
      this.showAuthorization = false;
    }
  }

  @Watch('$route')
  onRouteChange(to: Route, from: Route) {
    const { fullPath, meta } = from;
    if (to.meta.index > from.meta.index) {
      this.transitionName = 'slide-left';
      this.historyRouter.push({ fullPath, index: meta.index });
    } else {
      this.transitionName = 'slide-right';
      this.historyRouter.pop();
    }
  }

  public created() {
    if (this.accountInfo && this.accountInfo.acoid) {
      this.$socket.client.emit('init-manager', this.accountInfo, ({ result, message }: IResponse) => {
        if (result) {
          this.$message.success(message);
        } else {
          this.$message.error(message);
        }
      });
    } else {
      this.$message.error('当前用户未登录！');
    }
  }

  public render() {
    return (
      <div class={style['home']}>
        <div class={style['home-container']}>
          <transition name={this.transitionName}>
            <router-view />
          </transition>
        </div>
        {this.renderAuthorization()}
        <van-tabbar v-model={this.active} class={style['home-footer']} active-color='#20a5df'>
          <van-tabbar-item icon='todo-list' name='log'>
            日志
          </van-tabbar-item>
          <van-tabbar-item icon='wap-home' name='room-list'>
            主页
          </van-tabbar-item>
          <van-tabbar-item icon='friends' name='user'>
            用户
          </van-tabbar-item>
        </van-tabbar>
      </div>
    );
  }

  private renderAuthorization() {
    return (
      <van-dialog
        value={this.showAuthorization}
        before-close={(action: any, done: any) => {
          done(false);
        }}
        title='账号信息授权验证'
        theme='round-button'
        confirmButtonColor='#20a5df'
        confirmButtonText={this.loading ? '正 在 授 权 ... ' : '重 新 授 权'}
        on-confirm={this.handleConfirme}>
        <div class={style['authorization']}>
          <p>
            <span>1、</span> <span>当前用户账号信息错误，请检查爱智账号是否已登录，并授权成功？</span>{' '}
          </p>
          <p>
            <span>2、</span> <span>如果已登录，点击下方按钮重新授权！</span>{' '}
          </p>
        </div>
      </van-dialog>
    );
  }

  private handleConfirme() {
    this.$edger
      .user()
      .then(result => {
        if (result && result.acoid) {
          console.info(result);
          this.$store.commit('update', { accountInfo: result });
        } else {
          this.$message.error('授权失败，请退出重新授权！');
        }
      })
      .catch((error: Error) => {
        this.$message.error('授权失败，请退出重新授权！');
        throw error;
      })
      .finally(() => {
        this.loading = false;
      });
  }
}
